import moment from 'moment'
import { debounce } from 'lodash'

const DEFAULT_DEBOUNCE_MS = 500
const DEFAULT_DEBOUNCE_OPTIONS = { leading: true, trailing: false }
const DEFAULT_LIST_MAP_FUNC = (item) => ({ ...item })
const DEFAULT_EDIT_MAP_FUNC = (item) => ({ ...item })

export default {
  data() {
    return {
      listApi: null, // 分页接口
      createApi: null, // 创建接口
      updateApi: null, // 修改接口
      deleteApi: null, // 单个删除接口
      batchDeleteApi: null, // 批量删除接口
      tableLoading: false,
      tableData: [],
      selection: [],
      tableOption: {
        border: true,
        index: false,
        indexLabel: '序号',
        stripe: true,
        selection: true,
        reserveSelection: true,
        menuAlign: 'center',
        menuFixed: false,
        emptyBtnText: '重置',
        // emptyBtn: false,
        editBtn: true,
        delBtn: true,
        align: 'center',
        addBtn: true,
        viewBtn: true,
        searchShow: true,
        searchIcon: true,
        labelWidth: 120,
        menuWidth: 240,
        searchMenuSpan: 6,
        searchMenuPosition: 'left',
      },
      form: {},
      searchForm: {},
      daterange: [],
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        layout: 'total, sizes, prev, pager, next, jumper',
        background: true,
      },
      listMapFunc: DEFAULT_LIST_MAP_FUNC,
      editMapFunc: DEFAULT_EDIT_MAP_FUNC,
    }
  },
  methods: {
    onDateRangeChange(rg) {
      if (rg && rg.length > 1) {
        this.searchForm.beginDate = moment(rg[0]).format('YYYY-MM-DD HH:mm:ss')
        this.searchForm.endDate = moment(rg[1]).endOf('date').format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.searchForm.beginDate = null
        this.searchForm.endDate = null
      }
    },
    onRefresh() {
      this.loadListData(this.page, this.searchForm)
    },
    onSearchChange(form, done) {
      this.page.currentPage = 1
      this.loadListData(this.page, form)
      done()
    },
    onSearchReset() {
      this.daterange = []
      this.searchForm.beginDate = null
      this.searchForm.endDate = null
      this.page.currentPage = 1
      this.loadListData(this.page, this.searchForm)
    },
    onPageSizeChange(pageSize) {
      this.page.currentPage = 1
      this.page.pageSize = pageSize
      this.loadListData()
    },
    onPageIndexChange(currentPage) {
      this.page.currentPage = currentPage
      this.loadListData()
    },
    onSelectionChange(list) {
      this.selection = list
    },
    // 批量删除
    onBatchDeleteClick: debounce(
      async function () {
        const length = (this.selection || []).length
        if (length < 0) {
          this.$message.warning('选中后才能批量删除')
          return
        }

        try {
          await this.$confirm(`确定删除选中的${length}项吗?`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
        } catch (error) {
          console.log('取消')
          return
        }

        try {
          const { code, message } = await this.batchDeleteApi(this.selection)
          if (code === 200) {
            this.$message.success('批量删除成功')
            this.onRefresh()
          } else {
            this.$message.error(message)
          }
        } catch (error) {
          this.$message.success('批量删除失败')
        }
      },
      DEFAULT_DEBOUNCE_MS,
      DEFAULT_DEBOUNCE_OPTIONS
    ),
    // 新建
    onRowSave: debounce(
      async function (row, done, loading) {
        try {
          const params = this.editMapFunc(row)
          const { code, message } = await this.createApi(params)
          if (code === 200) {
            this.$message.success('新增成功')
            this.onRefresh()
            done()
          } else {
            this.$message.error(message)
            loading()
          }
        } catch (error) {
          console.log(error)
          this.$message.error('新增失败')
          loading()
        }
      },
      DEFAULT_DEBOUNCE_MS,
      DEFAULT_DEBOUNCE_OPTIONS
    ),
    // 编辑
    onRowUpdate: debounce(
      async function (row, index, done, loading) {
        try {
          const params = this.editMapFunc(row)
          const { code, message } = await this.updateApi(params)
          if (code === 200) {
            this.$message.success('编辑成功')
            this.onRefresh()
            done()
          } else {
            this.$message.error(message)
            loading()
          }
        } catch (error) {
          console.log(error)
          this.$message.error('编辑失败')
          loading()
        }
      },
      DEFAULT_DEBOUNCE_MS,
      DEFAULT_DEBOUNCE_OPTIONS
    ),
    // 删除
    onRowDelete: debounce(
      async function (form, index) {
        try {
          await this.$confirm('确定删除吗?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
        } catch (error) {
          console.log('取消')
          return
        }

        try {
          const { code, message } = await this.deleteApi({ id: form.id })
          if (code === 200) {
            this.$message.success('删除成功')
            /* Fix: BUG# 60906 当最后一页只有一条数据时，删除后界面内容为空 luoyongbing 2022-06-02 below */
            if (
              this.total % this.page.pageSize === 1 && // 最后一页只有一条数据
              this.page.pageSize * this.page.currentPage > this.total && // 在最后一页
              this.page.pageNo > 1 // 不在第一页
            ) {
              this.page.pageNo -= 1
            }
            /* Fix: BUG# 60906 当最后一页只有一条数据时，删除后界面内容为空 luoyongbing 2022-06-02 above */
            this.onRefresh()
          } else {
            this.$message.error(message)
          }
        } catch (error) {
          console.log(error)
          this.$message.error('删除失败')
        }
      },
      DEFAULT_DEBOUNCE_MS,
      DEFAULT_DEBOUNCE_OPTIONS
    ),
    // 分页列表
    loadListData: debounce(
      async function (page, params) {
        try {
          this.tableLoading = true
          const listParams = Object.assign(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
            },
            params,
            this.searchForm
          )
          const { success, data } = await this.listApi(listParams)
          if (success) {
            this.tableLoading = false
            this.tableData = ((data && data.records) || []).map(this.listMapFunc)
            this.page.total = data.total
            // FIX BUG: 多选没有及时清除 BELOW
            if (this.tableOption.selection) {
              // 多选列表
              this.$refs.crud && this.$refs.crud.selectClear()
            }
            // FIX BUG: 多选没有及时清除 ABOVE
          }
        } catch (err) {
          console.log(err)
          this.tableLoading = false
        }
      },
      DEFAULT_DEBOUNCE_MS,
      DEFAULT_DEBOUNCE_OPTIONS
    ),
    // 查看
    async loadRowDetails(row) {
      try {
        const { code, data } = await this.getApi({ id: row.id })
        if (code === 200) {
          return data
        } else {
          console.log(message)
        }
      } catch (error) {
        console.log(error)
      }

      return row
    },
  },
}
